export type TActionsService = ReturnType<typeof getServices>;

export function getServices() {
  const mapping = new Map<string, Map<string, Function>>();

  function register(componentId: string, actionName: string, func: Function) {
    if (!mapping.has(componentId)) {
      mapping.set(componentId, new Map());
    }

    const actionMap = mapping.get(componentId)!;
    actionMap.set(actionName, func);
  }

  function run(
    componentId: string,
    actionName: string,
    kwargs: Record<string, any>
  ) {
    if (!mapping.has(componentId)) {
      throw new Error("组件没有注册 action!");
    }
    const actionMap = mapping.get(componentId)!;
    if (!actionMap.has(actionName)) {
      throw new Error(`组件没有注册指定 action[${actionName}]!`);
    }
    actionMap.get(actionName)!(kwargs);
  }

  return {
    register,
    run,
  };
}
